
/****************************************
 * @Date: 2021-08-11 16:41:12
 * @LastEditors: Alonc
 * @LastEditTime: 2022-09-02 14:50:57
 */

export class ObjectUtil {
    /**
     * 判断指定的值是否为对象
     * @param value 值
     */
    static isObject( value: any ): boolean {
        return Object.prototype.toString.call( value ) === '[object Object]';
    }

    /**
     * 深拷贝
     * @param target 目标
     */
    static deepCopy( target: any ): any {
        if ( target == null || typeof target !== 'object' ) {
            return target;
        }

        let result: any = null;

        if ( target instanceof Date ) {
            result = new Date();
            result.setTime( target.getTime() );
            return result;
        }

        if ( target instanceof Array ) {
            result = [];
            for ( let i = 0, length = target.length; i < length; i++ ) {
                result[ i ] = this.deepCopy( target[ i ] );
            }
            return result;
        }

        if ( target instanceof Object ) {
            result = {};
            for ( const key in target ) {
                if ( target.hasOwnProperty( key ) ) {
                    result[ key ] = this.deepCopy( target[ key ] );
                }
            }
            return result;
        }

        console.warn( `不支持的类型：${ result }` );
    }

    /**
     * 拷贝对象
     * @param target 目标
     */
    static copy( target: object ): object {
        return JSON.parse( JSON.stringify( target ) );
    }

    // 数据求和
    static sum<T>( initData: T, ...args: T[] ): T {
        let result: any = initData;
        for ( let data of args ) {
            for ( let key in data ) {
                if ( result[ key ] !== undefined ) {
                    result[ key ] += data[ key ];
                }
            }
        }
        return result;
    }

    // 数据合并求和
    static mergeSum<T>( initData: T | any, key: string, value: number ): T {
        for ( let k in initData ) {
            if ( k === key ) {
                initData[ k ] += value;
            }
        }

        return initData;
    }

    // 遍历检测对象是否有 undefined 字段
    static checkUndefinedFields( obj: any ): boolean {
        let hasError: boolean = false;
        for ( const key in obj ) {
            if ( obj[ key ] === undefined ) {
                hasError = true;
                console.error( `Undefined field: ${ key } in request body` );
                return hasError;
            }
            if ( typeof obj[ key ] === 'object' && obj[ key ] !== null ) {
                hasError = this.checkUndefinedFields( obj[ key ] );
            }
        }
        return hasError;
    }
}
